"""
二分类
"""
import numpy as np
from sklearn.metrics import confusion_matrix as cm

file = '.\Classification.csv'

with open(file) as f:
    target = np.loadtxt(file, dtype=str, delimiter=",", skiprows=1, usecols=1)
    pre1 = np.loadtxt(file, dtype=str, delimiter=",", skiprows=1, usecols=2)
    pre2 = np.loadtxt(file, dtype=str, delimiter=",", skiprows=1, usecols=3)
    pre3 = np.loadtxt(file, dtype=str, delimiter=",", skiprows=1, usecols=4)


# 计算混淆矩阵函数
def conmat(pre):
    n = len(pre)
    tp = 0
    fn = 0
    fp = 0
    tn = 0
    # 分别计算tp,fn,fp,tn
    for i in range(0, n):
        if target[i] == "1.00" and pre[i] == "1.00":
            tp = tp + 1
        elif target[i] == "1.00" and pre[i] == "0.00":
            fn = fn + 1
        elif target[i] == "0.00" and pre[i] == "1.00":
            fp = fp + 1
        elif target[i] == "0.00" and pre[i] == "0.00":
            tn = tn + 1
    # print("tp:" + str(tp), "fn:" + str(fn), "fp:" + str(fp), "tn:" + str(tn))
    print(np.array([[tp, fn], [fp, tn]]))
    # 计算查准率P、查全率R、精度T和F1指数
    P = tp / (tp + fp)
    R = tp / (tp + fn)
    T = (tp + fn) / n
    F1 = (2 * tp) / (n + tp - tn)
    print("Precision:" + str(P), "Recall:" + str(R))
    print("精度:" + str(T), "错误率:" + str(1 - T), "F1:" + str(F1))


# 输出结果
print("pre1:"), conmat(pre1)
print("pre2:"), conmat(pre2)
print("pre3:"), conmat(pre3)

"""
# 调用库验证
tn_, fp_, fn_, tp_ = cm(target, pre1).ravel()
matrix = np.array([[tp_, fn_], [fp_, tn_]])
print(matrix)
"""
